class Task {
  constructor(form, name, value) {
    this.form = form
    this.name = name
    this.value = value
  }

  run() {}
}

import { request } from 'utils/http'
import { serialize } from 'utils'

class VisibilityTask extends Task {
  static name = 'visible'

  run() {
    const func = this.value ? 'showItem' : 'hideItem'
    return this.form[func].call(this.form, [this.name])
  }
}

class RequiredTask extends Task {
  static name = 'required'

  run() {
    const func = this.value ? 'requireItem' : 'unRequireItem'
    return this.form[func].call(this.form, [this.name])
  }
}

class EqualTask extends Task {
  static name = 'equal'

  run(currentName, propValue) {
    const func = this.value ? 'setValue' : 'clear'
    const formData = this.form['getValue'].call(this.form)
    this.goRefAction(formData, currentName, func, this.name, propValue)
    // return this.form[func].call(this.form, {...formData, [this.name]: "235"})
  }
  // 获取应用数据 进行task操作！  参数：checkId, key对象，alias表单别名 querySetting
  goRefAction(formData, currentName, func, thisName, propValue) {
    const _this = this
    var url = this.form.formUrl.replace("showForm","refAction")
    let dataLinkage = []
    this.form.models.meta.forEach(element => {
      if(element.name === currentName){
        dataLinkage = JSON.parse(element.dataLinkage)
      }
    });
    dataLinkage && dataLinkage.forEach(ele=> {
      let querySetting = []
      ele.groups.forEach(item=>{
        item.conditions.forEach(te=> {
          let obj = {
            name: te.propValue,
            value: formData[te.name],
            linkOpt: "AND",
            builder: te.compareType
          }
          querySetting.push(obj)
        })
      })
      request(url, {
        method: "POST",
        data: serialize({
          checkId: encodeURI(currentName),
          key: JSON.stringify(this.form.datas.key),
          alias: this.form.models.formAlias,
          querySetting: JSON.stringify(querySetting)
        }),
        headers: {
          "content-type": "application/x-www-form-urlencoded"
        }
        
      }).then(res => {
        const datas = res.datas.refData.rows[0]
        const formDataTimely = _this.form['getValue'].call(_this.form)
        _this.form[func].call(_this.form, {...formDataTimely, [thisName]: datas[propValue]})
      })
    })
    
  }
}

class GlobalTask extends Task {
  static GLOBAL_SYMBOL = 'global:'

  static isGlobal = (taskName) => {
    return taskName && taskName.startsWith(GlobalTask.GLOBAL_SYMBOL)
  }

  run() {
    // 目前 global 事件只支持显示、隐藏，所以此处未做区分
    this.form.$emit('global-event', this.name.replace(GlobalTask.GLOBAL_SYMBOL, ''), this.value)
  }
}

const taskMap = [VisibilityTask, RequiredTask, EqualTask].reduce((ret, item) => ({
  ...ret,
  [item.name]: item
}), {})

export const getWorker = (name, key) => {
  if (key && GlobalTask.isGlobal(key)) {
    return GlobalTask
  }

  return taskMap[name]
}
